// import router from '@/lib/router';
import Vue from 'vue';
import Router from 'vue-router';
import { setToken, setCookieTenant, setTenantId, getUserToken, setTokenType, removeToken, removeTokenType, removeCookieTenant, deleteTenantId } from '@/lib/auth'; // get token from cookie

Vue.use(Router);
import store from '@/extend/store';
import { beforeRouter, afterRouter } from '@/lib/router/permission';
import extendRouter from './module/index';
import { api_GET_UsersOrganizationUnit } from '@/extend/api/swaggerApi/identity';

// const whiteList = [/^\/[\s\S]+\/(register|info)/]; // no redirect whitelist
const whiteList = [/^\/home\/[\s\S]+\/info/];
const createRouter = (aRouterList) => new Router({
  // mode: 'history', // require service support
  scrollBehavior: () => ({ y: 0 }),
  routes: aRouterList
});

const router = createRouter(extendRouter);
// 路由跳转检测
router.beforeEach((to, from, next) => {
  if (!store.state.app.isgetBadge && to.params.id.indexOf('_plat') === -1) {
    // 嵌入式引用商城  需要重置登录信息及tenantid信息
    if (to.query.token) {
      store.commit('user/SET_TOKEN', to.query.token);
      setToken(to.query.token);
    } else {
      store.commit('user/SET_TOKEN', '');
      removeToken();
    }
    if (to.query.tenantid) {
      store.commit('user/SET_TENANTID', to.query.tenantid);
      setCookieTenant(to.query.tenantid);
      setTenantId(to.query.tenantid);
    } else {
      store.commit('user/SET_TENANTID', '');
      removeCookieTenant();
      deleteTenantId();
    }
    if (to.query.tokentype) {
      setTokenType(to.query.tokentype);
    } else {
      removeTokenType();
    }
  }
  if (!store.state.app.isgetBadge && !/^\/myCenter/.test(to.path)) {
    let tenantId = to.params.id
      ? to.params.id.lastIndexOf('_') > -1 && to.params.id.split('_')[1] !== 'plat'
        ? to.params.id.split('_')[1]
        : ''
      : '';
    tenantId = tenantId || to.query.tenantid;
    setCookieTenant(tenantId);
  }
  // if (store.state.user.token && store.state.user.currentUserType) {
  //   initToDo(to, next);
  // }
  beforeRouter(to, from, next, store, router, extendRouter, whiteList, initToDo);
  // 处理跳转/myCenter的问题
  // if (store.state.user.currentUserType && store.state.user.currentUserType.userType && to.path === '/myCenter') {
  //   const userType = store.state.user.currentUserType && store.state.user.currentUserType.userType || {};
  //   if (userType.code === 'Delegation') {
  //     next({ path: '/myCenter/team/info' });
  //   } else {
  //     next({ path: '/myCenter/individual/info' });
  //   }
  // } else {
  next();
  // }
});

router.afterEach(() => {
  afterRouter();
});

// 初始化只执行一次的操作
async function initToDo (to, next) {
  const _toPath = to.path;
  const _delegationId = store.state.user.currentUserType.delegationId;
  const _info = store.state.user.info;
  if (!store.state.app.isgetBadge) {
    await getUserToken();
  }
  // 跳转到团体
  if (_toPath.indexOf('/myCenter/team') > -1 || _toPath.indexOf('/myCenter/approval') > -1) {
    /**
     * 团体信息的展示
     * (1) 在后台中没有加入机构 - 新账号（可以创建团体）
     * (2) 在后台中加入了机构且有团体会员管理（EventsManagement.Competitions.MembersManagement）权限
    */
    if (!_delegationId) {
      try {
        const res = await api_GET_UsersOrganizationUnit();
        if (!res) {
          next();
        } else {
          next({ path: '/404' });
        }
      } catch (error) {
        next({ path: '/404' });
      }
      // api_GET_UsersOrganizationUnit().then(res => {
      //   if (!res) {
      //     next();
      //   } else {
      //     next({ path: '/404' });
      //   }
      // });
    } else if (_delegationId && _info.permissions.includes('EventsManagement.Competitions.MembersManagement')) {
      next();
    } else {
      next({ path: '/404' });
    }
  }
  return true;
}

export default router;
